# Python 2.6.4
# Project Euler, Problem 61
# Copyright 2010 Talha Zaman

def P(m, n):
    if m==3: return n*(n+1)/2
    elif m==4: return n**2
    elif m==5: return n*(3*n-1)/2
    elif m==6: return n*(2*n-1)
    elif m==7: return n*(5*n-3)/2
    elif m==8: return n*(3*n-2)
    else: return 0

def cycle(first, prev, left, p):
    if prev==0:
        rem = left[:]
        poly = rem.pop()
        for num in p[poly]:
            c = cycle(num, num, rem, p)
            if c: return [num] + c
    elif len(left)==1:
        rem = left[:]
        poly = rem.pop()
        for num in p[poly]:
            if str(num) == str(prev)[-2:] + str(first)[:2]: return [num]
        return None
    else:
        for poly in left:
            rem = left[:]
            rem.remove(poly)
            for num in p[poly]:
                if str(num)[:2] == str(prev)[-2:]:
                    c = cycle(first, num, rem, p)
                    if c: return [num] + c
        return None

p = [[] for i in range(6)]
for i in range(1, 150):
    for j in range(6):
        num = P(j+3, i)
        if 999<num<10000: p[j].append(num)
c = cycle(0, 0, [0,1,2,3,4,5], p)
print c, sum(c)
